package com.uyayo.framework.captcha;

import com.uyayo.framework.captcha.model.GeneralCaptcha;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 常规验证码引擎
 * @author hfj
 * @date 2018/10/20
 */
public class GeneralGraphicsEngine {
    /**
     * 随机产生的字符串ABCDEFGHIJKLMNOPQRSTUVWXYZ
      */
    private String randomStr = "0123456789";
    /**
     * 最大的两位数
     */
    private int maxDoubleDigit = 99;

    /**
     * 字体名称
     */
    private String fontName = "Arial";

    /**
     * 字体大小
     */
    private int fontSize = 23;

    private Random random = new Random();
    /**
     * 图片宽
     */
    private int imgWidth = 80;
    /**
     * 图片高
     */
    private int imgHeight = 28;
    /**
     * 干扰线数量
     */
    private int lineNum = 20;

    /**
     * 随机产生字符数量
     */
    private int randomStrNum = 4;

    public String getRandomStr() {
        return randomStr;
    }

    public void setRandomStr(String randomStr) {
        this.randomStr = randomStr;
    }

    public int getMaxDoubleDigit() {
        return maxDoubleDigit;
    }

    public void setMaxDoubleDigit(int maxDoubleDigit) {
        this.maxDoubleDigit = maxDoubleDigit;
    }

    public String getFontName() {
        return fontName;
    }

    public void setFontName(String fontName) {
        this.fontName = fontName;
    }

    public int getFontSize() {
        return fontSize;
    }

    public void setFontSize(int fontSize) {
        this.fontSize = fontSize;
    }

    public Random getRandom() {
        return random;
    }

    public void setRandom(Random random) {
        this.random = random;
    }

    public int getImgWidth() {
        return imgWidth;
    }

    public void setImgWidth(int imgWidth) {
        this.imgWidth = imgWidth;
    }

    public int getImgHeight() {
        return imgHeight;
    }

    public void setImgHeight(int imgHeight) {
        this.imgHeight = imgHeight;
    }

    public int getLineNum() {
        return lineNum;
    }

    public void setLineNum(int lineNum) {
        this.lineNum = lineNum;
    }

    public int getRandomStrNum() {
        return randomStrNum;
    }

    public void setRandomStrNum(int randomStrNum) {
        this.randomStrNum = randomStrNum;
    }

    public GeneralGraphicsEngine() {
    }

    public GeneralGraphicsEngine(int imgWidth,
                                 int imgHeight,
                                 int lineNum,
                                 int fontSize,
                                 String fontName,
                                 int randomStrNum,
                                 String randomStr,
                                 int maxDoubleDigit) {
        this.imgWidth = imgWidth;
        this.imgHeight = imgHeight;
        this.lineNum = lineNum;
        this.fontSize = fontSize;
        this.fontName = fontName;
        this.randomStrNum = randomStrNum;
        this.randomStr = randomStr;
        this.maxDoubleDigit = maxDoubleDigit;
    }

    /**
     * 生成普通数字的随机图片
     */
    public GeneralCaptcha genRandomCodeImage(StringBuffer randomCode, int width, int height) {
        // BufferedImage类是具有缓冲区的Image类
        BufferedImage img = new BufferedImage(width, height,BufferedImage.TYPE_4BYTE_ABGR);
        //产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
        Graphics2D g = (Graphics2D)img.getGraphics();
        img = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g = img.createGraphics();

        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        for (int i = 1; i <= randomStrNum; i++) {
            randomCode.append(drawString(g, i));
        }
        for (int i = 0; i <= lineNum; i++) {
            drawLine(g);
        }
        g.dispose();

        GeneralCaptcha captcha = new GeneralCaptcha();
        captcha.setImage(img);
        captcha.setCode(randomCode.toString());
        captcha.setCreateTime(System.currentTimeMillis());
        return captcha;
    }

    /**
     * 生成普通数字的随机图片
     */
    public GeneralCaptcha genRandomCodeImage(StringBuffer randomCode) {
        return genRandomCodeImage(randomCode, imgWidth, imgHeight);
    }

    /**
     * 生成四则运算的随机图片
     *
     * @param randomCode 验证码图片的结果值
     * @param width      宽度
     * @param height     高度
     * @return 图片 image
     */
    public GeneralCaptcha genArithRandomCodeImage(StringBuffer randomCode, int width, int height) {
        // BufferedImage类是具有缓冲区的Image类
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_BGR);
        // 获取Graphics对象,便于对图像进行各种绘制操作
        Graphics2D g = (Graphics2D) image.getGraphics();
        // 设置背景色
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);

        // 设置干扰线的颜色
        g.setColor(getRandColor(110, 120));

        // 绘制干扰线
        for (int i = 0; i <= lineNum; i++) {
            drawLine(g);
        }
        // 绘制随机字符
        g.setFont(new Font(fontName, Font.ROMAN_BASELINE, fontSize));

        int firstNum = random.nextInt(maxDoubleDigit);
        int secondNum = random.nextInt(maxDoubleDigit);
        String logicalSymbol = getLogicalSymbol();
        //减法时设置 第一个随机数为两个数当中最大的那个
        if (logicalSymbol.equals("减") && firstNum - secondNum < 0) {
            int tempNum = firstNum;
            firstNum = secondNum;
            secondNum = tempNum;
        }
        //验证码结果值
        randomCode.append(String.valueOf(getCalculateResult(firstNum, secondNum, logicalSymbol)));

        drawString(g, 0, String.valueOf(firstNum));
        drawString(g, 13, logicalSymbol);
        drawString(g, 27, String.valueOf(secondNum));
        drawString(g, 40, "等");
        drawString(g, 52, "于");
        drawString(g, 63, "？");

        g.dispose();

        GeneralCaptcha captcha = new GeneralCaptcha();
        captcha.setImage(image);
        captcha.setCode(randomCode.toString());
        captcha.setCreateTime(System.currentTimeMillis());

        return captcha;
    }

    /**
     * 生成四则运算的随机图片
     */
    public GeneralCaptcha genArithRandomCodeImage(StringBuffer randomCode) {
        return genArithRandomCodeImage(randomCode, imgWidth, imgHeight);
    }

    /**
     * 给定范围获得随机颜色
     */
    private Color getRandColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    /**
     * 绘制字符串
     */
    private String drawString(Graphics g, int i) {
        g.setFont(getFont());
        g.setColor(Color.BLACK);
        String rand = String.valueOf(getRandomString(random.nextInt(randomStr
                .length())));
        rand = rand.toUpperCase();
        //g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 13*i, 23);
        return rand;
    }

    /**
     * 绘制干扰线
     */
    private void drawLine(Graphics2D g) {
        int x = random.nextInt(imgWidth);
        int y = random.nextInt(imgHeight);
        int x0 = random.nextInt(16);
        int y0 = random.nextInt(16);
        Stroke stroke=new BasicStroke(1.5f);//设置线宽为1.5f
        g.setStroke(stroke);
        g.drawLine(x, y, x + x0, y + y0);
    }
    /**
     * 获得字体
     */
    private Font getFont(){
        return new Font(fontName,Font.ITALIC,fontSize);
    }
    /**
     * 获取随机的字符
     */
    private String getRandomString(int num) {
        return String.valueOf(randomStr.charAt(num));
    }


    /**
     * 绘制字符串
     */
    private String drawString(Graphics g, int x, String rand) {
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
                .nextInt(121)));
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, x, 18);
        return rand;
    }

    /**
     * 随机获取四则运算字符的中文值
     */
    private String getLogicalSymbol() {
        String logicalSymbol;
        //加减乘除 （暂时不考虑乘除）
        int asmd = random.nextInt(2);
        switch (asmd) {
            case 0:
                logicalSymbol = "加";
                break;
            case 1:
                logicalSymbol = "减";
                break;
            case 2:
                logicalSymbol = "乘";
                break;
            case 3:
                logicalSymbol = "除";
                break;
            default:
                logicalSymbol = "加";
                break;
        }
        return logicalSymbol;
    }

    /**
     * 获取验证码结果值
     */
    private int getCalculateResult(int firstNum, int secondNum, String logicalSymbol) {
        int result = 0;
        if (logicalSymbol.equals("加")) {
            result = firstNum + secondNum;
        }
        if (logicalSymbol.equals("减")) {
            result = firstNum - secondNum;
        }
        if (logicalSymbol.equals("乘")) {
            result = firstNum * secondNum;
        }
        if (logicalSymbol.equals("除")) {
            result = firstNum / secondNum;
        }
        return result;
    }
}
